#include <board.h>
#include <board_memories.h>
#include <tsd/tsd.h>
#include <tsd/inarea.h>
#include <lcd/lcdd.h>
#include <lcd/draw.h>
#include <pit/pitd.h>
#include <pio/pio.h>
#include <menu.h>
#include <menu_list.h>
#include <viewer.h>
#include <memories/MEDSdcard.h>

static unsigned char *_lcd_buffer = (unsigned char *) (AT91C_EBI_SDRAM + 0x01000000);

//------------------------------------------------------------------------------
// VIEWER

static void viewer (void) {
    viewer_open(0);
}

//------------------------------------------------------------------------------
// MENU

static menu_list_t items;

static void selection (int idx) {
    menu_item_t item;

    if (idx == MENU_BACK) {
        menu_list_init(&items, "..");
        goto _menu_config_new_items;
    }

    menu_list_get(&item, &items, idx);
    if (item.flags & MENU_ITEM_IS_DIR) {
        menu_list_init(&items, item.name);
        _menu_config_new_items:
        menu_configure_items(&items);
        return;
    }

    menu_exit();
}

static void menu (void) {
    menu_configure_items(&items);
    menu_draw(_lcd_buffer);
}

//------------------------------------------------------------------------------
// MAIN

Media sdcard;

int main() {
    FATFS fs = {0};

    // Initialize LCD
    LCDD_Fill(_lcd_buffer, COLOR_WHITE);
    LCDD_Initialize();
    LCDD_DisplayBuffer(_lcd_buffer);

#if !defined(sdram)
    BOARD_ConfigureSdram(BOARD_SDRAM_BUSWIDTH);
#endif

    /*MEDSdcard_Initialize(&sdcard, 0);
    f_mount(DRV_MMC, &fs);
    f_chdrive(DRV_MMC);
    f_chdir("0:");
    MEDSdcard_Disable();*/

    TSD_Initialize(0);
    PITD_Configure(TSD_Update_PenState, 10000, 0);
    TSD_SetPitPeriod(10);
    PITD_Start();
    while (!TSD_Calibrate(_lcd_buffer))
        ;
    PITD_Stop();

    MEDSdcard_Initialize(&sdcard, 0);
    f_mount(DRV_MMC, &fs);
    f_chdrive(DRV_MMC);
    f_chdir("0:");
    MEDSdcard_Disable();
    TSD_Resume();

    LCDD_Fill(_lcd_buffer, COLOR_WHITE);
    viewer_init();
    menu_init();
    menu_configure_callback(selection);

    menu_list_init(&items, ".");

    while (1) {
        menu();
        viewer();
    }

    return 0;
}
